package cn.linkstudy.service.impl;

import cn.linkstudy.entity.ChatRecord;
import cn.linkstudy.mapper.ChatRecordMapper;
import cn.linkstudy.service.ChatRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class ChatRecordServiceImpl implements ChatRecordService {
    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Override
    public void saveRecord(ChatRecord record) {
        chatRecordMapper.insert(record);
    }

    @Override
    public List<ChatRecord> getFirstMessagesByUser(Long userId) {
        return chatRecordMapper.selectList(
                new QueryWrapper<ChatRecord>()
                        .eq("user_id", userId)
                        .eq("is_first", 1)
                        .orderByDesc("create_time"));
    }

    @Override
    public String createNewSession(Long userId, String grade, String knowledgePoint) {
        String sessionId = java.util.UUID.randomUUID().toString();
        // 不再插入数据库，只生成sessionId
        return sessionId;
    }

    @Override
    public List<ChatRecord> getUserChats(Long userId, String sessionId) {
        QueryWrapper<ChatRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        if (sessionId != null) {
            queryWrapper.eq("session_id", sessionId);
        }
        queryWrapper.orderByAsc("create_time");
        return chatRecordMapper.selectList(queryWrapper);
    }

    @Override
    public ChatRecord getHistory(Long userId, String sessionId) {
        QueryWrapper<ChatRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("session_id", sessionId)
                .orderByDesc("create_time")
                .last("LIMIT 1");
        return chatRecordMapper.selectOne(queryWrapper);
    }
}